import store from "../store/index";
import router from "../router";
import axios from "axios";
import { ElMessage } from "element-plus";
//
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// import {useStore} from "vuex"
// //
// const store = useStore();
import {
  nprogressConfig,
  defaultConfig,
  throttleExecutor,
  isRequestSuccess,
} from "./config";
//
import { tipError } from "../utils/tip";
// import { saveLocal, getLocal } from "@/utils/storage";
//
// nprogress 配置
NProgress.configure(nprogressConfig);
// @ts-ignore
axios.defaults.baseURL = $location.origin;
const http = axios.create(defaultConfig);
//

// 拦截 request 请求
http.interceptors.request.use((config) => {
  // 开启 ngprogress
  NProgress.start();
  // 添加自定义请求头
  if (!config.headers) {
    config.headers = {};
  }
  if (config.headers?.['Blade-Auth'] == undefined) {
    config.headers['Blade-Auth'] = `Bearer ${store.getters.token}`;
  }
  for (const k in config.headers) {
    const v = config.headers[k];
    if (v === false) {
      delete config.headers[k];
    }
  }
  // 增加节流功能
  config.cancelToken = new axios.CancelToken((c) => {
    throttleExecutor(config, c);
  });
  //
  return config;
});

let is401 = false;
// 拦截 response
http.interceptors.response.use(
  (resp) => {
    // 关闭 ngprogress
    NProgress.done();
    // 解析接口状态 返回为 true 则正常返回 数据 若为 false 则返回 异常
    // if (!isRequestSuccess(resp)) {
    //   return Promise.reject(resp);
    // }
    // 拦截规则
    return resp;
  },
  (error) => {
    is401 = false;
    // 关闭 ngprogress
    NProgress.done();
    //

    const resp = error.response;
    const data = resp?.data || {};
    // const currentPath = router.currentRoute.value.path;
    // console.log("==========", data, resp);
    const msg = data.msg || data.message || resp.statusText;
    const isJumpLogin = store.getters.loginStatus ? false : true;
    //
    switch (resp?.status) {
      case 404:
        // 跳 400 页面
        router.push(isJumpLogin ? "/" : "/404");
        break;
      case 401:
        is401 = true;
        router.push(isJumpLogin ? "/" : "/401");
        // 跳 401 页面
        break;
      case 403:
        break;
      case 500:
        break;
      case 503:
        break;
      default:
        break;
    }
    // 是否提示
    !isJumpLogin && tipError(msg);
    // 返回错误信息
    return isJumpLogin ? resp : Promise.reject(resp);
  }
);

//

export default http;
